package com.htjc.integral.conversion.tokenUtil;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import oracle.sql.TIMESTAMP;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.htjc.integral.model.conversion.EcPartner;

import lombok.extern.slf4j.Slf4j;

/**
 * @author:李宇
 * @data:2014年8月20日 @time:下午4:06:55
 * @Described:CommonTools.java 基本工具类
 */
@Slf4j(topic = "exchangeLogger")
public class CommonTools {

//	static Logger log = Logger.getLogger(CommonTools.class.getCanonicalName());
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
	SimpleDateFormat sdfms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
			Locale.CHINA);

	/**
	 * 将字符串转换为16进制字符串
	 * 
	 * @param str
	 * @return String
	 */
	@SuppressWarnings("deprecation")
	public String transformStringTo16(String str) {
		return URLEncoder.encode(str);
	}

	public String subString(String str) {
		if (str != null) {
			return str.substring(0, str.length() > 14 ? 14 : str.length());
		}
		return "";
	}

	// 截取字符串
	public String subStringEnhance(String str, int num) {
		if (str == null || str == "") {
			return "";
		}
		return str.substring(0, str.length() > num ? num : str.length());
	}

	// 将 str = "Mon May 05 19:42:40 CST 2014";格式的字符串转化为date
	public String dateFormat(Date date, String parm) {
		// Date date = parse(str, "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
		if (null == date) {
			return "";
		}
		// DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		DateFormat format1 = new SimpleDateFormat(parm);
		String str = format1.format(date);

		return str;// System.out.printf("%tF %<tT%n", date);
	}

	public String convernTimeToString(TIMESTAMP Timestamp)
			throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.parse(Timestamp.toString()).toLocaleString();
	}

	/**
	 * 判断手机号
	 * 
	 * @param moble
	 * @return
	 */
	public boolean validateMoble(String moble) {
		// String rexgx = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
		String rexgx = "^[1][3578]\\d{9}$";
		Pattern p = Pattern.compile(rexgx);
		Matcher m = p.matcher(moble);
		boolean flag = m.matches();
		return flag;
	}

	/**
	 * 邮箱验证
	 * 
	 * @param email
	 * @return
	 */
	public boolean validateEmail(String email) {
		String rexEmail = "^(\\w-*\\.*)+@(\\w-?)+(\\.\\w{2,})+$";
		Pattern p = Pattern.compile(rexEmail);
		Matcher m = p.matcher(email);
		boolean flag = m.matches();
		return flag;
	}

	/**
	 * 根据积分金额计算积分
	 * 
	 * @param maxIntegralMoneyb
	 * @return
	 */
	public int getRefundIntel(String maxIntegralMoneyb) {
		int intel = 0;
		BigDecimal dintel = new BigDecimal(maxIntegralMoneyb);
		BigDecimal intelTemp = new BigDecimal(200).multiply(dintel);
		intel = intelTemp.intValue();
		return intel;
	}

	/**
	 * velocity 页面比较时间
	 * 
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public int getDateCompare(String date) throws ParseException {
		java.util.Date nowdate = new java.util.Date();
		String _nowdate = sdf.format(nowdate);
		int flag_2 = _nowdate.compareTo(date);
		return flag_2;
	}

	/**
	 * mongodb用户信息映射Partner实体
	 * 
	 * @param jsonString
	 * @return EcPartner
	 * @throws Exception
	 */
	public EcPartner userInfoJsonToPartner(String jsonString) throws Exception {
		EcPartner partner = new EcPartner();
		try {
			if (StringUtils.isNotBlank(jsonString)) {
				JSONObject json = JSON.parseObject(jsonString);
				log.info("转换之前用户信息：" + json);
				/*
				 * json.put("partnerId", json.getString("originId"));
				 * json.remove("originId"); json.remove("thirdBind");
				 * json.remove("tenementId"); json.remove("appId");
				 * json.remove("appCode"); EcPartner partner =
				 * json.parseObject(json.toJSONString(), EcPartner.class);
				 */

				// 用户安全信息 如果属性值不一一对应时 再用
				partner.setPartnerId(json.containsKey("userId") ? json
						.getString("userId") : "");
				partner.setLoginAccount(json.containsKey("loginAccount") ? json
						.getString("loginAccount") : "");
				partner.setPassword(json.containsKey("password") ? json
						.getString("password") : "");
				partner.setUserType(json.containsKey("userType") ? json
						.getString("userType") : "1");
				partner.setApplyWay(json.containsKey("applyWay") ? json
						.getString("applyWay") : "");
				partner.setMobile(json.containsKey("mobile") ? json
						.getString("mobile") : "");
				partner.setMobileActivationSign(json
						.containsKey("mobileActivationSign") ? json
						.getString("mobileActivationSign") : "");
				partner.setEmail(json.containsKey("email") ? json
						.getString("email") : "");
				partner.setEmailActivationSign(json
						.containsKey("emailActivationSign") ? json
						.getString("emailActivationSign") : "");
				partner.setFromIpAddress(json.containsKey("fromIpAddress") ? json
						.getString("fromIpAddress") : "");// 来源ip
				partner.setFromSgProvice(json.containsKey("fromSgProvice") ? json
						.getString("fromSgProvice") : "");
				partner.setLoginFailTimes(json.containsKey("loginFailTimes") ? json
						.getString("loginFailTimes") : "");
				partner.setLockType(json.containsKey("lockType") ? json
						.getString("lockType") : "");
				partner.setUnlockDate(checkDateJson(json, "unlockDate"));// 解锁时间
				partner.setRegisterTime(checkDateJson(json, "registerTime"));// 注册时间
				partner.setVerifyIdea(json.containsKey("verifyIdea") ? json
						.getString("verifyIdea") : "");// 审核意见
			    partner.setPasswordUpdateTime(checkDateJson(json, "passwordUpdateTime"));
				partner.setMemberStatus(json.containsKey("memberStatus") ? json
						.getString("memberStatus") : "");// 会员状态;0=初始;1=审核中;2=已审批;3=审批不通过
				partner.setMarketType(json.containsKey("marketType") ? json
						.getString("marketType") : "");// 商城类别

				// 用户基本信息
				partner.setName(json.containsKey("name") ? json
						.getString("name") : "");
				partner.setNickname(json.containsKey("nickname") ? json
						.getString("nickname") : "");
				partner.setHobby(json.containsKey("hobby") ? json
						.getString("hobby") : "");
				partner.setPhoto(json.containsKey("photo") ? json
						.getString("photo") : "");
				partner.setPost(json.containsKey("post") ? json
						.getString("post") : "");
				partner.setSex(json.containsKey("sex") ? json.getString("sex")
						: "");
				partner.setEducation(json.containsKey("education") ? json
						.getString("education") : "");
				partner.setBirthday(checkDateJson(json, "birthday"));// 生日
				partner.setAddressCity(json.containsKey("addressCity") ? json
						.getString("addressCity") : null);
				partner.setAddressCountry(json.containsKey("addressCountry") ? json
						.getString("addressCountry") : "");
				partner.setAddressDetail(json.containsKey("addressDetail") ? json
						.getString("addressDetail") : "");
				partner.setAddressProvince(json.containsKey("addressProvince") ? json
						.getString("addressProvince") : "");
				partner.setAddressRegion(json.containsKey("addressRegion") ? json
						.getString("addressRegion") : "");
				// 用户其他信息
				partner.setSchoolName(json.containsKey("schoolName") ? json
						.getString("schoolName") : "");
				partner.setSchoolScience(json.containsKey("schoolScience") ? json
						.getString("schoolScience") : "");
				partner.setSchoolType(json.containsKey("schoolType") ? json
						.getString("schoolType") : "");
				partner.setMarriage(json.containsKey("marriage") ? json
						.getString("marriage") : "");
				partner.setIncome(json.containsKey("income") ? json
						.getString("income") : "");
				partner.setIndustry(json.containsKey("industry") ? json
						.getString("industry") : "");
				partner.setIdcard(json.containsKey("idcard") ? json
						.getString("idcard") : "");
				partner.setWorkBegintime(json.containsKey("workBegintime") ? json
						.getString("workBegintime") : "");
				partner.setWorkInstitution(json.containsKey("workInstitution") ? json
						.getString("workInstitution") : "");

				// 等级积分信息
				partner.setRankChangeDate(checkDateJson(json, "rankChangeDate"));// 等级变更
				partner.setRankNumber(json.containsKey("rankNumber") ? json
						.getString("rankNumber") : "");// 等级
				partner.setNowIntegral(json.containsKey("nowIntegral") ? json
						.getString("nowIntegral") : "");// 当年剩余积分
				partner.setExperience(json.containsKey("experience") ? json
						.getString("experience") : "");// 经验值
				/*
				 * //企业升级 商户入驻信息
				 * partner.setHandlerOffice(json.containsKey("originId"
				 * )?json.getString("originId"):"");
				 * partner.setAccno(json.containsKey
				 * ("originId")?json.getString("originId"):"");
				 * partner.setAccountLicenseUrl
				 * (json.containsKey("originId")?json.getString("originId"):"");
				 * 
				 * partner.setBank(json.containsKey("originId")?json.getString(
				 * "originId"):"");
				 * partner.setBankAccount(json.containsKey("originId"
				 * )?json.getString("originId"):"");
				 * partner.setBankAccountType(json
				 * .containsKey("originId")?json.getString("originId"):"");
				 * partner
				 * .setBankAddress(json.containsKey("originId")?json.getString
				 * ("originId"):"");
				 * partner.setBankBranchName(json.containsKey("originId"
				 * )?json.getString("originId"):"");
				 * 
				 * partner.setBusinessField(json.containsKey("originId")?json.
				 * getString("originId"):"");
				 * partner.setBusinessLicense(json.containsKey
				 * ("originId")?json.getString("originId"):"");
				 * partner.setBusinessLicenseUrl
				 * (json.containsKey("originId")?json.getString("originId"):"");
				 * partner
				 * .setBusinessLimitDate(json.containsKey("originId")?json
				 * .getString("originId"):"");
				 * partner.setBusinessLocation(json.containsKey
				 * ("originId")?json.getString("originId"):"");
				 * partner.setCompanyAddress
				 * (json.containsKey("originId")?json.getString("originId"):"");
				 * partner
				 * .setCompanyName(json.containsKey("originId")?json.getString
				 * ("originId"):"");
				 * partner.setCompanyNumofpeople(json.containsKey
				 * ("originId")?json.getString("originId"):"");
				 * partner.setCompanyTelephone
				 * (json.containsKey("originId")?json.getString("originId"):"");
				 * partner
				 * .setCompanyUrl(json.containsKey("originId")?json.getString
				 * ("originId"):"");
				 * partner.setCompanyVerifyState(json.containsKey
				 * ("originId")?json.getString("originId"):"");
				 * partner.setContactMobile
				 * (json.containsKey("originId")?json.getString("originId"):"");
				 * partner
				 * .setContactPerson(json.containsKey("originId")?json.getString
				 * ("originId"):"");
				 * partner.setCustomerServiceTel(json.containsKey
				 * ("originId")?json.getString("originId"):"");
				 * 
				 * 
				 * partner.setIdcartFrontUrl(json.containsKey("originId")?json.
				 * getString("originId"):"");
				 * partner.setIdcartReverseUrl(json.containsKey
				 * ("originId")?json.getString("originId"):"");
				 * partner.setIdcartType
				 * (json.containsKey("originId")?json.getString("originId"):"");
				 * partner
				 * .setIsBalanceAccount(json.containsKey("originId")?json.
				 * getString("originId"):"");
				 * partner.setIsExpresscompany(json.containsKey
				 * ("originId")?json.getString("originId"):"");
				 * partner.setIsFacilitator
				 * (json.containsKey("originId")?json.getString("originId"):"");
				 * partner
				 * .setIsGoodservicer(json.containsKey("originId")?json.getString
				 * ("originId"):"");
				 * partner.setIsLogisticservicer(json.containsKey
				 * ("originId")?json.getString("originId"):"");
				 * partner.setIsVisitedMember
				 * (json.containsKey("originId")?json.getString("originId"):"");
				 * partner
				 * .setItins(json.containsKey("originId")?json.getString("originId"
				 * ):"");
				 * partner.setItinsUrl(json.containsKey("originId")?json.getString
				 * ("originId"):"");
				 * partner.setOrganizationCode(json.containsKey
				 * ("originId")?json.getString("originId"):"");
				 * partner.setOrganizationCodeUrl
				 * (json.containsKey("originId")?json.getString("originId"):"");
				 * partner
				 * .setTaxregisterLicense(json.containsKey("originId")?json
				 * .getString("originId"):"");
				 * partner.setTaxregisterLicenseUrl(json
				 * .containsKey("originId")?json.getString("originId"):"");
				 * partner
				 * .setLastyearIntegral(json.containsKey("originId")?json.
				 * getString("originId"):"");
				 * partner.setLegalRepLocate(json.containsKey
				 * ("originId")?json.getString("originId"):"");
				 * partner.setPriceBalance
				 * (json.containsKey("originId")?json.getString("originId"):"");
				 * //保证金余额
				 * partner.setRegCapital(json.containsKey("originId")?json
				 * .getString("originId"):"");//注册资金
				 * 
				 * //支付信息
				 * partner.setPaymentLoginAccount(json.containsKey("originId"
				 * )?json.getString("originId"):"");
				 * partner.setPaymentStatus(json
				 * .containsKey("originId")?json.getString("originId"):"");
				 * partner
				 * .setPayplatformLoginpw(json.containsKey("originId")?json
				 * .getString("originId"):"");
				 * partner.setPayplatformPaypw(json.containsKey
				 * ("originId")?json.getString("originId"):"");
				 */
				partner.setIntegralCleartime(checkDateJson(json,
						"integralCleartime"));
				// partner.setIntegralCleartime(json.containsKey("originId")?json.getDate("originId"):"");//最近积分清除时间
				log.error("json转Partner用户实体成功，PartnerId:"
						+ partner.getPartnerId() + ",loginAccount:"
						+ partner.getLoginAccount());
				return partner;
			} else {
				log.error("用户信息json为空");
				return null;
			}
		} catch (Exception e) {
			log.error("json转换Partner实体异常", e);
			// return null;
			throw new Exception(e);
		}
		
	}

	private Date checkDate(String value) {
		Date date = null;
		if (StringUtils.isNotBlank(value)) {
			try {
				long date_temp = Long.valueOf(value);
				date = new Date(date_temp * 1000L);
			} catch (Exception e) {
				try {
					date = sdfms.parse(value);
				} catch (ParseException e1) {
					log.error("时间转换异常", e1);
				}
			}
		}
		return date;
	}

	private Date checkDateJson(JSONObject json, String key) {
		Date date = null;
		if (json.containsKey(key) && json.get(key) != null
				&& json.get(key) != "") {
			try {
				date = json.getDate(key);
			} catch (Exception e) {
				try {
					String value = json.getString(key);
					if (value.indexOf("/") > -1) {
						String[] split = value.split("/");
						if (split[0].length() == 2) {
							split[0] = "20" + split[0];
						}
						if (split[2].split(":").length == 2) {
							split[2] += ":00";
						}
						String string = new String();
						for (int i = 0; i < split.length; i++) {
							if (i == split.length - 1) {
								string += split[i];
							} else {
								string += split[i] + "-";
							}
						}
						log.info("格式化之前属性{key：" + key + ",value:"
								+ json.get(key) + "}");
						json.put(key, string);
						date = json.getDate(key);
					} else {
						log.info("格式化日期失败的属性{key：" + key + ",value:"
								+ json.get(key) + "}");
					}
				} catch (Exception e2) {
					log.error(
							"格式化日期异常！属性{key：" + key + ",value:" + json.get(key)
									+ "}", e2);
				}
			}
		}
		return date;
	}

	public static void main(String[] args) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("time", "16/01/24 13:35");
		Date checkDateJson = new CommonTools()
				.checkDateJson(jsonObject, "time");
		System.out.println(checkDateJson);
	}

	public static final String jsonResult(boolean success, int resultCode,
			String resultMessage, Object resultData) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", success);
		map.put("resultCode", resultCode);
		map.put("resultMessage", resultMessage);
		map.put("result", resultData != null ? resultData : "");
		String jsonString = JSON.toJSONString(map);
		log.info("CommonTools返回结果：" + jsonString);
		return jsonString;
	}
}
